package edu.chinasoft.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import edu.chinasoft.domain.Function;
import edu.chinasoft.domain.Role;
import edu.chinasoft.service.RoleService;

/**
 *
 * @author mhao
 * @date 2020年2月12日:下午3:56:48
 * @version V1.0
 * @Description: 
*/
@WebServlet(name="myUpdateRoleServlet",value="/servlet/updateroleservlet")
public class UpdateRoleServlet extends HttpServlet {
	private static Logger logger = LoggerFactory.getLogger(UpdateRoleServlet.class);
	private RoleService roleService;
	/**
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info(" UpdateRoleServlet >doGet start.......");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		RoleService roleServiceImp = wac.getBean("roleService", RoleService.class);
		this.roleService=roleServiceImp;
		//获取更新后的角色信息
		String role_id = request.getParameter("role_id");
		String role_name = request.getParameter("role_name");
		String functions = request.getParameter("functions");
		Role role = new Role();
		role.setRoleId(Integer.parseInt(role_id));
		role.setRoleName(role_name);
		String[] functionArray = functions.split("、");
		List<Function> functionList = new ArrayList<Function>();
		for(int index=0;index<functionArray.length;index++) {
			Function function = new Function();
			function.setFunctionName(functionArray[index]);
			functionList.add(function);
		}
		logger.info("角色需更新的权限为："+functionList);
		role.setFunctionList(functionList);
		Boolean result = roleService.updateRoleByRoleId(role);
		if(result) {
			//更新成功
			response.sendRedirect(""+request.getContextPath()+"/servlet/showroleservlet");
		}else {
			//更新失败
			response.sendRedirect(""+request.getContextPath()+"/updateroleerror.jsp");
		}
		logger.info(" UpdateRoleServlet >doGet end.......");
	}

	/**
	 *
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info(" UpdateRoleServlet >doPost start.......");
		this.doGet(request, response);
		logger.info(" UpdateRoleServlet >doPost end.......");
	}

}